package com.itheima.Service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.Mapper.*;
import com.itheima.Service.UserOrderService;

import com.itheima.exception.BusinessException;

import com.itheima.pojo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;

import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserOrderServiceImpl implements UserOrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private InventoryMapper inventoryMapper;

    @Override
    public PageResult<OrderVO> page(UserOrderQueryParam queryParam) {
        PageHelper.startPage(queryParam.getPage(), queryParam.getPageSize());
        List<OrderVO> orderList = orderMapper.listForUser(queryParam);
        Page<OrderVO> page = (Page<OrderVO>) orderList;

        // 查询每个订单的商品列表
        for (OrderVO order : orderList) {
            List<OrderItem> items = orderItemMapper.listByOrderId(order.getId());
            order.setOrderItems(items);
        }

        return new PageResult<>((int) page.getTotal(), orderList);
    }

    @Override
    public OrderDetailVO get(Integer userId, Integer orderId) {
        // 查询订单基本信息
        Order order = orderMapper.get(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 校验订单归属
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权访问该订单");
        }

        // 构建订单详情VO
        OrderDetailVO detailVO = new OrderDetailVO();
        detailVO.setOrder(order);

        // 查询订单商品
        List<OrderItem> items = orderItemMapper.listByOrderId(orderId);
        detailVO.setOrderItems(items);

        // 查询收货地址
        UserAddress address = userAddressMapper.get(order.getAddressId());
        detailVO.setAddress(address);

        return detailVO;
    }

    @Override
    @Transactional
    public String create(Integer userId, OrderCreateParam createParam) {
        // 1. 校验商品信息和库存
        List<OrderItemCreateParam> itemParams = createParam.getItems();
        List<OrderItem> orderItems = new ArrayList<>();
        BigDecimal totalAmount = BigDecimal.ZERO;

        for (OrderItemCreateParam itemParam : itemParams) {
            Product product = productMapper.get(itemParam.getProductId());
            if (product == null || !product.getStatus().equals("1")) {
                throw new BusinessException("商品不存在或已下架");
            }

            // 检查库存
            Integer stock = inventoryMapper.getStock(itemParam.getProductId());
            if (stock == null || stock < itemParam.getQuantity()) {
                throw new BusinessException("商品库存不足");
            }

            // 计算小计，增加空值判断
            BigDecimal itemAmount = BigDecimal.ZERO;
            product.setPrice(BigDecimal.valueOf(product.getDiscountPrice()));
            itemAmount = product.getPrice().multiply(new BigDecimal(itemParam.getQuantity()));

            totalAmount = totalAmount.add(itemAmount);

            // 构建订单项
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(product.getId());
            orderItem.setProductName(product.getName());
            orderItem.setProductImage(product.getImage());
            orderItem.setPrice(product.getPrice());
            orderItem.setQuantity(itemParam.getQuantity());
            orderItem.setAmount(itemAmount);

            orderItems.add(orderItem);
        }

        // 2. 生成订单
        Order order = new Order();
        order.setUserId(userId);
        order.setOrderNumber(generateOrderNumber());
        order.setStatus(String.valueOf(OrderStatus.PENDING));
        order.setPaymentStatus(String.valueOf(PaymentStatus.PENDING));
        order.setAddressId(createParam.getAddressId());
        order.setAmount(totalAmount);
        order.setRemark(createParam.getRemark());
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        orderMapper.insert(order);
        log.info("订单生成成功：{}", order);
        // 3. 插入订单项
        for (OrderItem item : orderItems) {
            item.setOrderId(Math.toIntExact(order.getId()));
            orderItemMapper.insert(item);
        }

        // 4. 扣减库存
        for (OrderItemCreateParam itemParam : itemParams) {
            inventoryMapper.reduceStock(itemParam.getProductId(), itemParam.getQuantity());
        }

        return order.getOrderNumber();
    }

    @Override
    @Transactional
    public void cancel(Integer userId, Integer orderId) {
        // 1. 查询订单
        Order order = orderMapper.get(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 2. 校验订单归属和状态
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作该订单");
        }

        if (!OrderStatus.canCancel(order.getStatus())) {
            throw new BusinessException("订单状态不允许取消");
        }

        // 3. 更新订单状态
        order.setStatus(String.valueOf(OrderStatus.CANCELLED));
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.update(order);

        // 4. 如果已付款，需要发起退款流程
        if (order.getPaymentStatus().equals(String.valueOf(PaymentStatus.PAID))) {
            // 调用支付服务退款
            // refundService.refund(order.getOrderNumber());

            // 更新支付状态
            order.setPaymentStatus(String.valueOf(PaymentStatus.REFUNDING));
            orderMapper.updatePaymentStatus(order.getId(), PaymentStatus.REFUNDING);
        }

        // 5. 恢复库存
        List<OrderItem> items = orderItemMapper.listByOrderId(orderId);
        for (OrderItem item : items) {
            inventoryMapper.increaseStock(item.getProductId(), item.getQuantity());
        }
    }

    @Override
    @Transactional
    public void confirm(Integer userId, Integer orderId) {
        // 1. 查询订单
        Order order = orderMapper.get(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 2. 校验订单归属和状态
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作该订单");
        }

        if (!order.getStatus().equals(String.valueOf(OrderStatus.SHIPPED))) {
            throw new BusinessException("订单状态不允许确认收货");
        }

        // 3. 更新订单状态为已完成
        order.setStatus(String.valueOf(OrderStatus.COMPLETED));
        order.setCompleteTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.update(order);
    }

    @Override
    @Transactional
    public void applyRefund(Integer userId, Integer orderId, RefundApplyParam applyParam) {
        // 1. 查询订单
        Order order = orderMapper.get(orderId);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 2. 校验订单归属和状态
        if (!order.getUserId().equals(userId)) {
            throw new BusinessException("无权操作该订单");
        }

        if (!OrderStatus.canApplyRefund(order.getStatus())) {
            throw new BusinessException("订单状态不允许申请退款");
        }

        // 3. 创建退款记录
        Refund refund = new Refund();
        refund.setOrderId(orderId);
        refund.setRefundNumber(generateRefundNumber());
        refund.setAmount(order.getAmount());
        refund.setReason(applyParam.getReason());
        refund.setStatus("pending"); // 待处理
        refund.setCreateTime(LocalDateTime.now());

        // refundMapper.insert(refund);

        // 4. 更新订单状态
        order.setStatus(String.valueOf(OrderStatus.REFUNDING));
        order.setUpdateTime(LocalDateTime.now());
        orderMapper.update(order);

        // 5. 如果已发货，需要调用物流服务退回
        if (order.getStatus().equals(String.valueOf(OrderStatus.SHIPPED))) {
            // logisticsService.returnGoods(order.getOrderNumber());
        }
    }

    // 生成订单号
    private String generateOrderNumber() {
        return "ORD" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6);
    }

    // 生成退款号
    private String generateRefundNumber() {
        return "REF" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 6);
    }
    /**
     * 毕设专用：支付订单（直接修改状态为已付款）
     */
    @Override
    @Transactional // 加事务保证数据一致性
    public void payOrder(Integer userId, Integer orderId) {
        // 1. 查询订单
        Order order = orderMapper.get(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }

        // 2. 校验订单归属（防止别人支付别人的订单）
        if (!order.getUserId().equals(userId)) {
            throw new RuntimeException("无权操作此订单");
        }

        // 3. 校验订单状态（只能支付“待付款”状态的订单）
        if (!"pending".equals(order.getStatus())) {
            throw new RuntimeException("当前订单状态无法支付（仅待付款订单可支付）");
        }

        // 4. 修改订单状态为“已付款”
        order.setStatus("paid"); // 已付款状态
        order.setPaymentStatus("paid");// 已付款状态
        order.setPayTime(LocalDateTime.now());// 记录支付时间
        order.setUpdateTime(LocalDateTime.now());// 记录更新时间
        orderMapper.update(order);

        log.info("订单{}支付成功，状态已更新为已付款", orderId);
    }

    @Override
    public List<Order> selectOrdersListById(Integer userId) {
        return orderMapper.selectOrdersListById(userId);
    }
}